package com.grm.service.impl;

import com.google.code.kaptcha.Producer;
import com.grm.common.Result;
import com.grm.constant.UserConstant;
import com.grm.exception.BusinessException;
import com.grm.service.CaptchaService;
import com.grm.util.RedisUtil;
import com.grm.util.UUIDUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.FastByteArrayOutputStream;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class CaptchaServiceImpl implements CaptchaService {
    @Resource
    private Producer captchaProducer;
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public Result getCaptcha() {
        String text = captchaProducer.createText();
        BufferedImage image;
        image = captchaProducer.createImage(text);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", os);
        } catch (IOException e) {
            throw new BusinessException(e.getMessage());
        }
        String uuid = UUIDUtil.get32UUID();
        // redis存captcha,60s有效期
        redisUtil.setExpire(UserConstant.getCaptchaKey(uuid),text,60, TimeUnit.SECONDS);
        Map<String,String> resultMap = new HashMap<>();
        resultMap.put("uuid", uuid);
        resultMap.put("captcha",Base64.getEncoder().encodeToString(os.toByteArray()));
        return Result.success(resultMap);
    }
}
